package com.kasax.plugin.app.transform

import com.android.build.api.transform.*
import com.android.build.gradle.internal.pipeline.TransformManager
import com.android.utils.FileUtils
import com.kasax.plugin.app.visitor.lifecycle.MethodCostClassVisitor
import org.gradle.api.Project
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter

/**
 * https://juejin.cn/post/7368693416832253987
 */
class MethodCostTimeTransform extends Transform {
    final String TAG = "ActivityLifeCountTransform"


    Project project

    MethodCostTimeTransform(Project proj) {
        this.project = proj
    }

    // 设置我们自定义的Transform对应的Task名称
    // 类似：transformClassesWithPreDexForXXX
    // 这里应该是：transformClassesWithInjectTransformForxxx
    @Override
    String getName() {
        return "ActivityLifeCountTransform"
    }

    @Override
    Set<QualifiedContent.ContentType> getInputTypes() {
        return TransformManager.CONTENT_CLASS
    }

    @Override
    Set<? super QualifiedContent.Scope> getScopes() {
        return TransformManager.SCOPE_FULL_PROJECT
    }

    @Override
    boolean isIncremental() {
        return false
    }

    @Override
    void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
        def inputs = transformInvocation.inputs
        def outputProvider = transformInvocation.outputProvider
        inputs.forEach {
            TransformInput transformInput ->
                // 处理目录
                transformInput.directoryInputs.forEach { DirectoryInput directoryInput ->
                    if (directoryInput.file.isDirectory()) {
                        FileUtils.getAllFiles(directoryInput.file).forEach { File file ->
                            def fileName = file.name
                            //找到所有以Activity结尾的class文件（要注意这里不是.kotlin或者是.java文件而是.class文件）
                            if (fileName.endsWith("Activity.class")) {
                                //找到需要的。class文件，进行一系列读写操作
                                def classPath = file.absolutePath
                                def classReader = new ClassReader(file.readBytes())
                                def classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_MAXS)
                                def visitior = new MethodCostClassVisitor(classWriter)
                                classReader.accept(visitior, ClassReader.SKIP_FRAMES)

                                def bytes = classWriter.toByteArray()
                                def fos = new FileOutputStream(classPath)
                                fos.write(bytes)
                                fos.close()
                            }
                        }
                    }
                    def dest = outputProvider.getContentLocation(
                            directoryInput.name,
                            directoryInput.contentTypes,
                            directoryInput.scopes,
                            Format.DIRECTORY
                    )
                    FileUtils.copyDirectoryToDirectory(directoryInput.file, dest)
                }

                // 处理jar
                transformInput.jarInputs.forEach { JarInput jarInput ->
                    def dest = outputProvider.getContentLocation(
                            jarInput.getName(),
                            jarInput.contentTypes,
                            jarInput.scopes,
                            Format.JAR
                    )
                    FileUtils.copyFile(jarInput.file, dest)
                }

        }
    }
}